<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/1/27
 * Time: 17:43
 */

namespace App\HttpController\Admin;


use App\Model\AdminsModel;
use App\Model\CatesModel;
use App\Model\VideosCountModel;
use App\Model\VideosModel;
use Carbon\Carbon;

class VideoController extends AuthController
{
    /**
     * 视频管理_列表
     */
    public function index(){
        $request = $this->request();
        $page = (int)$request->getRequestParam('page')??0;
        if($page < 1){
            $page = 1;
        }
        $sort = $request->getRequestParam('sort')??0;
        switch ($sort) {
            case 1:
                $sort = 'view';
                break;
            case 2:
                $sort = 'share';
                break;
            default:
                $sort = 'id';
                break;
        }

        $where = [
            'title' => (string)$request->getRequestParam('name')??'',
            'chanel_id' => (int)$request->getRequestParam('chanel_id')??0,
            'option' => (int)$request->getRequestParam('option')??0,
            'banner' => (int)$request->getRequestParam('banner')??0,
            'status' => (int)$request->getRequestParam('status')??0,
            'userid' => (int)$request->getRequestParam('admins')??0,
            'start' => $request->getRequestParam('start')??'',
            'end' => $request->getRequestParam('end')??'',
        ];

        $videoModel = new VideosModel();
        if($where['title']){
            $videoModel->where('title','%'.$where['title'].'%','like');
        }
        if($where['chanel_id'] > 0){
            $videoModel->where('chanel_id',$where['chanel_id']);
        }
        if($where['option'] > 0){
            $videoModel->where('`option`',$where['option']);
        }
        if($where['banner'] > 0){
            $videoModel->where('banner',$where['banner']);
        }
        if($where['status'] > 0){
            $videoModel->where('videos.status',$where['status']);
        }
        if($where['userid']){
            $videoModel->where('videos.userid',$where['userid']);
        }
        if($where['start']){
            $videoModel->where('videos.created_at',$where['start'],'>=');
        }
        if($where['end']){
            $videoModel->where('videos.created_at',$where['end'],'<=');
        }
        $videoModel->select('admins.nickname,videos.*')->join('admins','videos.userid = admins.id','LEFT');
        $videoModel->orderBy($sort, 'DESC');
        $list = $videoModel->paginate($page);
        $this->stateToText($list['data'], [
            'status' => VideosModel::STATUS_TEXT,
            'option' => VideosModel::OPTION_TEXT,
            'banner' => VideosModel::BANNER_TEXT,
        ]);

        // 统计
        $videoCount = new VideosModel();
        if($where['title']){
            $videoCount->where('title',$where['title']);
        }
        if($where['chanel_id'] > 0){
            $videoCount->where('chanel_id',$where['chanel_id']);
        }
        if($where['option'] > 0){
            $videoCount->where('`option`',$where['option']);
        }
        if($where['banner'] > 0){
            $videoCount->where('banner',$where['banner']);
        }
        if($where['status'] > 0){
            $videoCount->where('status',$where['status']);
        }
        if($where['userid']){
            $videoCount->where('userid',$where['userid']);
        }
        if($where['start']){
            $videoCount->where('created_at',$where['start'],'>=');
        }
        if($where['end']){
            $videoCount->where('created_at',$where['end'],'<=');
        }
        $videoCount->get();
        $msg['count']['share'] = $videoCount->sum('share');
        $msg['count']['view'] = $videoCount->sum('view');
        $adminsModel = new AdminsModel();
        $msg['admins'] = $adminsModel->select('id,nickname')->get();
        return $this->writeJson(0,$list,$msg);
    }

    /**
     * 视频管理_更新
     */
    public function update(){
        $request = $this->request();
        $params = $request->getRequestParam();
        $vid = self::getVideo($params['link']);
        if (!$vid) {
            return $this->writeJson(1, null,'视频链接有误');
        }
        $params['userid'] = $this->userid;
        $videoModel = new VideosModel();
        if(isset($params['id']) && (int)$params['id'] > 0){
            //编辑
            $info = $videoModel->find($params['id']);
            if (!$info) {
                return $this->writeJson(1, null,'数据不存在');
            }
            unset($params['userid']);
            $params['updated_at'] = Carbon::now();
            $isUpdate = $videoModel->update($params);
            if(!$isUpdate){
                return $this->writeJson(1, null,'系统错误');
            }
            return $this->writeJson(0, null,'编辑视频信息成功');
        }
        //新增
        if(isset($params['id'])){
            unset($params['id']);
        }
        //判断数据是否存在，去重（标题&链接ID）
        $videoModel->where('title',$params['title']);
        $videoModel->where('link','%'.$vid.'%','like','or');
        $is_video = $videoModel->first();
        if($is_video){
            return $this->writeJson(1, null,'该视频已经存在！');
        }
        $catesModel = new CatesModel();
        $catesOne = $catesModel->getRandOne();
        $params['cate_id'] = $catesOne['id'];
        $params['view'] = 0;
        $params['share'] = 0;
        $params['created_at'] = Carbon::now();
        $params['updated_at'] = $params['created_at'];
        $params['rand_cate'] = rand(1, 10);//随机分类，用于详情页随机展示列表
        $isSave = $videoModel->create($params);
        if(!$isSave){
            return $this->writeJson(1, null,'系统错误');
        }
        return $this->writeJson(0, $params);
    }
    /**
     * 解析视频地址
     */
    protected function getVideo($url){
        //获取腾讯视频真实地址
        if (strstr($url, 'v.qq.com')) {
            //匹配腾讯链接拿到所需的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $url, $matchs);
            if ($result) {
                return $matchs[1][0];
            }
        }
        return false;
    }

    /**
     * 视频管理_删除
     */
    public function destroy()
    {
        $request = $this->request();
        $id = (int)$request->getRequestParam('id')??0;
        if($id === 0){
            return $this->writeJson(1, null,'参数错误');
        }
        $videoModel = new VideosModel();
        $videoModel->where('status',1);
        $isDelete = $videoModel->destroy($id);
        $one =  $videoModel->find($id);
        if(!$isDelete || $one){
            return $this->writeJson(1, null,'删除失败');
        }
        return $this->writeJson(0, null,'删除成功');
    }

    /**
     * 视频管理_批量视频删除
     */
    public function destroyAll()
    {
        $request = $this->request();
        $lists = $request->getRequestParam('data');
        $videoModel = new VideosModel();
        $videoModel->where('status',1);
        if (count($lists) > 1) {
            $videoModel->whereIn('id',$lists);
            $isDelete = $videoModel->delete();
            if($isDelete){
                return $this->writeJson(0, null,'删除成功');
            }
        }elseif(count($lists) === 1){
            $isDelete = $videoModel->destroy($lists[0]);
            if($isDelete){
                return $this->writeJson(0, null,'删除成功');
            }
        }
        return $this->writeJson(1, '删除失败');
    }

    /**
     * 统计分析
     */
    public function count(){
        $request = $this->request();
        $params = $request->getRequestParam();

        $countModel = new VideosCountModel();
        if(!isset($params['start'])){
            $params['start'] = Carbon::now()->subDays(31)->toDateString();
        }

        $lists = $countModel->where('date',$params['start'],'>=')
            ->where(function ($query) use($params){
                if(isset($params['id']) && (int)$params['id'] > 1){
                    $query->where('admin_id',$params['id']);
                }
                if(isset($params['end']) && $params['end']){
                    $query->where('date',$params['end'],'<=');
                }
            })->select('sum(views) as views, sum(share_in) as share_in,date')
                ->groupBy('date')
                ->orderBy('date','ASC')
                ->get();
        return $this->writeJson(0,$lists);
    }

}
